<template>
  <px-dialog v-model="dialogVisible" :title="title" width="1000px">
    <px-scrollbar v-loading="loading" height="500px">
      <px-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="fab-add-device-form" status-icon label-position="left">
        <div class="label-title">基础信息</div>
        <px-row :gutter="16" :style="{ width: '100%' }">
          <px-col :span="12">
            <px-form-item label="机台编号" prop="eqpId">
              <deviceInput ref="deviceInputRef" v-model="ruleForm.eqpId" placeholder="请输入机台编号" @change="changeDeviceHandler" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="机台名称" prop="eqpName">
              <px-input v-model.trim="ruleForm.eqpName" clearable :disabled="disabledInfo.eqpNameDisabled" placeholder="请输入机台名称" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="区域" prop="areaId">
              <px-select v-model="ruleForm.areaId" clearable filterable :disabled="disabledInfo.areaIdDisabled" placeholder="请选择区域">
                <px-option v-for="item in areaIdOption" :key="item.value" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="柱位" prop="columnPlace">
              <px-input v-model.trim="ruleForm.columnPlace" clearable :disabled="disabledInfo.columnPlaceDisabled" placeholder="请输入柱位" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="设备工程师" prop="eeOwner">
              <px-input v-model.trim="ruleForm.eeOwner" clearable :disabled="disabledInfo.eeOwnerDisabled" placeholder="请输入设备工程师" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="工艺工程师" prop="peOwner">
              <px-input v-model.trim="ruleForm.peOwner" clearable :disabled="disabledInfo.peOwnerDisabled" placeholder="请输入工艺工程师" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="设备值班电话" prop="eePhone">
              <px-input v-model.trim="ruleForm.eePhone" clearable :disabled="disabledInfo.eePhoneDisabled" placeholder="请输入设备值班电话" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="工艺值班电话" prop="pePhone">
              <px-input v-model.trim="ruleForm.pePhone" clearable :disabled="disabledInfo.pePhoneDisabled" placeholder="请输入工艺值班电话" />
            </px-form-item>
          </px-col>

          <px-col :span="12">
            <px-form-item label="关系绑定" prop="eqpRelationCodeList">
              <deviceCascader
                ref="deviceCascaderRef"
                v-model="ruleForm.eqpRelationCodeList"
                :eqpId="ruleForm.eqpId"
                :disabled="!ruleForm.eqpId"
                placeholder="请选择绑定关系"
                @change="changeCascaderHandler"
              />
            </px-form-item>
          </px-col>
        </px-row>
        <px-form-item label="图片信息" prop="pictures">
          <ReUploadImage v-model="ruleForm.pictures" :limit="20" />
        </px-form-item>
        <px-form-item label="文档信息" prop="files">
          <ReUploadFile v-model="ruleForm.files" :limit="50" />
        </px-form-item>
      </px-form>
    </px-scrollbar>

    <template #footer>
      <span class="dialog-footer">
        <px-button @click="dialogVisible = false">取消</px-button>
        <px-button type="primary" :loading="submitLoading" @click="submitForm(ruleFormRef)"> 提交 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { PxMessage } from "px-ui";
import type { FormInstance, FormRules } from "px-ui";
import deviceInput from "./deviceInput.vue";
import deviceCascader from "./deviceCascader.vue";
import { createFabInfo, getFabDetail, editFabInfo, getFabAreaSelectOptions } from "@/api/modules/fab";
import { ReUploadFile, ReUploadImage } from "@/components/ReUpload";

const dialogVisible = defineModel({ type: Boolean, default: false });

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  eqpId: {
    type: [Number, String],
    required: true
  },
  id: {
    type: [Number, String],
    required: true
  }
});

const emits = defineEmits(["close", "submit"]);

const title = computed(() => {
  switch (props.type) {
    case "add":
      return "添加机台";
    case "edit":
      return "编辑机台";
    default:
      return "添加机台";
  }
});

const loading = ref<boolean>(false);
const submitLoading = ref<boolean>(false);
const deviceInputRef = ref<InstanceType<typeof deviceInput> | null>(null);
const deviceCascaderRef = ref<InstanceType<typeof deviceCascader> | null>(null);
const deviceRelationRemin = reactive<Array<any>>([]);
const areaIdOption = ref<Array<any>>([]);
const disabledInfo = ref<Record<string, boolean>>({
  eqpNameDisabled: true,
  areaIdDisabled: true,
  columnPlaceDisabled: true,
  eeOwnerDisabled: true,
  peOwnerDisabled: true,
  eePhoneDisabled: true,
  pePhoneDisabled: true
});

interface RuleForm {
  // factoryId: string;
  eqpId: string;
  eqpStatus: string;
  model: string;
  eqpName: string;
  areaId: string;
  columnPlace: string;
  eeOwner: string;
  peOwner: string;
  eePhone: string;
  pePhone: string;
  eqpRelationCodeList: Array<any>;
  pictures: Array<string>;
  files: Array<string>;
}
const ruleFormRef = ref<InstanceType<typeof FormInstance>>();
const ruleForm = reactive<RuleForm>({
  // factoryId: null,
  eqpId: null,
  eqpStatus: null,
  model: null,
  eqpName: null,
  areaId: null,
  columnPlace: null,
  eeOwner: null,
  peOwner: null,
  eePhone: null,
  pePhone: null,
  eqpRelationCodeList: [],
  pictures: [],
  files: []
});

const rules = reactive<FormRules<RuleForm>>({
  eqpId: [{ required: true, message: "请输入EQP_ID", trigger: "change" }],
  eqpName: [{ required: true, message: "请输入EQP_Name", trigger: "change" }],
  areaId: [{ required: true, message: "请选择区域", trigger: "change" }],
  columnPlace: [{ required: true, message: "请输入柱位", trigger: "change" }],
  eeOwner: [{ required: false, message: "请输入EE Owner", trigger: "change" }],
  peOwner: [{ required: false, message: "请输入PE Owner", trigger: "change" }],
  eePhone: [{ required: false, message: "请输入EE Phone", trigger: "change" }],
  pePhone: [{ required: false, message: "请输入PE Phone", trigger: "change" }],
  eqpRelationCodeList: [{ required: false, message: "请选择绑定关系", trigger: "change" }],
  pictures: [{ required: false, message: "请上传图片", trigger: "change" }],
  files: [{ required: false, message: "请上传图片", trigger: "change" }]
});

const getFabAreaSelectOptionsFn = async () => {
  const res = await getFabAreaSelectOptions(null, () => {
    loading.value = false;
  });
  areaIdOption.value = res
    .map(({ areaId: value = null, areaCode: label = null }: any) => ({ value, label }))
    ?.filter(({ value, label }) => !!value && !!label);
};

const submitForm = async (formEl: InstanceType<typeof FormInstance> | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      submitLoading.value = true;
      const eqpRelationList = [...deviceRelationRemin];
      const params = { ...ruleForm, eqpRelationList };
      delete params.eqpRelationCodeList;
      if (props.type === "add") {
        await createFabInfo(params, () => {
          loading.value = false;
          submitLoading.value = false;
        });
      } else {
        params["id"] = props.id;
        await editFabInfo(params, () => {
          loading.value = false;
          submitLoading.value = false;
        });
      }
      loading.value = false;
      submitLoading.value = false;
      dialogVisible.value = false;
      const la = props.type === "add" ? "添加" : "编辑";
      PxMessage({
        message: `${la} 成功`,
        type: "success"
      });
      emits("submit");
    } else {
      console.warn("error submit!", fields);
    }
  });
};

const changeCascaderHandler = val => {
  deviceRelationRemin.splice(0);
  if (!val?.length) return;
  deviceRelationRemin.push(...val);
};

const changeDeviceHandler = async (val: any, flag: boolean = false, flag2: boolean = true) => {
  deviceCascaderRef.value.clearHandler();
  ruleForm.eqpName = null;
  ruleForm.areaId = null;
  ruleForm.columnPlace = null;
  ruleForm.eeOwner = null;
  ruleForm.peOwner = null;
  ruleForm.eePhone = null;
  ruleForm.pePhone = null;
  if (val) {
    const {
      isCustom = false,
      // factoryId = null,
      eqpId = null,
      eqpName = null,
      eqpStatus = null,
      model = null,
      areaId = null,
      columnPlace = null,
      eeOwner = null,
      peOwner = null,
      eePhone = null,
      pePhone = null
    } = val;
    // ruleForm.factoryId = factoryId;
    ruleForm.eqpId = eqpId;
    // eqpStatus 如果没值，先写死一个，不报错就行   王建伟说的   20240928
    ruleForm.eqpStatus = eqpStatus || "RUN";
    ruleForm.model = model;
    ruleForm.eqpName = eqpName;
    ruleForm.areaId = areaId;
    ruleForm.columnPlace = columnPlace;
    ruleForm.eeOwner = eeOwner;
    ruleForm.peOwner = peOwner;
    ruleForm.eePhone = eePhone;
    ruleForm.pePhone = pePhone;
    disabledInfo.value.eqpNameDisabled = !flag2 ? flag2 : !!eqpName;
    disabledInfo.value.areaIdDisabled = !flag2 ? flag2 : !!areaId;
    disabledInfo.value.columnPlaceDisabled = !flag2 ? flag2 : !!columnPlace;
    disabledInfo.value.eeOwnerDisabled = !flag2 ? flag2 : !!eeOwner;
    disabledInfo.value.peOwnerDisabled = !flag2 ? flag2 : !!peOwner;
    disabledInfo.value.eePhoneDisabled = !flag2 ? flag2 : !!eePhone;
    disabledInfo.value.pePhoneDisabled = !flag2 ? flag2 : !!pePhone;
  }
  await nextTick();
  !flag && (await deviceCascaderRef.value.init());
};

const initData = async () => {
  if (props.eqpId) {
    const fabList = await deviceInputRef.value.remoteMethod(ruleForm.eqpId);
    const res: Record<string, any> = await getFabDetail(props.eqpId, () => {
      loading.value = false;
    });
    if (res) {
      await changeDeviceHandler(res, true, !!fabList?.length);
      const { eqpRelationList = [], pictures = [], files = [] } = res;
      const deviceRelationReminCodeList = eqpRelationList.map(item => {
        const { twoSystemCode = "", twoSystemName = "", takeOffs = [] } = item;
        let code = "";
        let name = "";
        if (takeOffs?.length) {
          code = takeOffs[0];
          name = takeOffs[0];
        } else {
          code = twoSystemCode;
          name = twoSystemName;
        }
        item["code"] = code;
        item["name"] = name;
        return item;
      });
      deviceRelationRemin.splice(0);
      deviceRelationRemin.push(...deviceRelationReminCodeList);
      deviceCascaderRef.value.deviceRelationList.push(...deviceRelationReminCodeList);
      ruleForm.eqpRelationCodeList = deviceRelationReminCodeList?.map(item => item.code);
      ruleForm.pictures = pictures;
      ruleForm.files = files;
    }
  }
};

const init = async () => {
  loading.value = true;
  await getFabAreaSelectOptionsFn();
  await initData();
  loading.value = false;
};

onMounted(async () => {
  await init();
});
</script>

<style scoped lang="scss">
.fab-add-device-form {
  padding-right: 10px;

  .label-title {
    margin-bottom: 16px;
    font-size: 15px;
    font-weight: 600;
    color: #555;
  }

  .px-form-item__content {
    .px-select {
      width: 100%;
    }
  }

  // 应测试（雪辉）要求去掉自动校验icon
  :deep(.px-form-item) {
    .px-input__validateIcon {
      display: none;
    }
  }
}
</style>
